package com.zqwm.fly.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zqwm.fly.mapper.BaseMapper;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * Service基类
 * @param <D>
 * @param <T>
 */
public abstract class BaseService<D extends BaseMapper<T>, T >{

    /*** 日志对象*/
    private static Logger logger = LoggerFactory.getLogger(BaseService.class);

    /*** 持久层对象*/
    @Autowired
    protected D dao;

    /* 保存数据（插入) @throws Exception*/
    @Transactional
    public boolean save(T entity)
    {
        try {dao.insert(entity);return true;}catch(Exception e){
        	logger.error("dao.insert", e);
        	return false;}
    }

    /*** 删除数据* @param id*/
    public boolean delete(Integer id)
    {
        try {dao.delete(id);return true;}catch (Exception e){
        	logger.error("dao.delete", e);
        	return false;}
    }

    /*** 批量删除* @param ids*/
    @Transactional(readOnly = false)
    public boolean deleteByIds(String ids)
    {
        try {String[] arrIds = ids.split(",");
        for (String id : arrIds){
        	dao.deleteByIds(id);}return true;}catch (Exception e){
        	logger.error("dao.deleteByIds", e);
        	return false;}
    }

    /**更新数据*/
    public boolean update(T entity){try{dao.update(entity);return true;}catch (Exception e){
    	logger.error("dao.update", e);
    	return false;}}


    /*** 查询列表数据@param entity@return*/
    public List<T> list(T entity) {return dao.selectByParams(entity);}

    /*** 通过map集合查询数据* @param map* @return*/
    public List<T> list(Map<String,Object>map) {return dao.selectByMap(map);}

    /**
     * 分页查询数据
     * @param entity
     * @param pageNum
     * @param pageSize
     * @return
     */
    public PageInfo pageByParams(T entity,Integer pageNum,Integer pageSize)
    {
        pageNum = pageNum == null || pageNum < 0 ? 1 : pageNum;
        pageSize = pageSize == null || pageSize < 0 ? 20 : pageSize;
        PageHelper.startPage(pageNum, pageSize);

        List<T>list = dao.selectByParams(entity);
        PageInfo pageInfo = new PageInfo(list);
        //Page page = (Page) list;
        return pageInfo;

    }

    /**
     * 分页查询数据
     * @param map
     * @param pageNum
     * @param pageSize
     * @return
     */
    public List<T>pageByParams(Map<String,Object>map,Integer pageNum,Integer pageSize)
    {
        pageNum = pageNum == null || pageNum < 0 ? 1 : pageNum;
        pageSize = pageSize == null || pageSize < 0 ? 20 : pageSize;
        PageHelper.startPage(pageNum, pageSize);

        return dao.selectByMap(map);
    }
}